<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .box{width:100px;height:100px;background: red;position: absolute;left:0;top:0;}
  </style>
</head>
<body>
  <div class="box"></div>
</body>
<script src="./cookie.js"></script>
<script>

  class Drag{
    constructor(){
      this.ele = document.querySelector(".box");

      // 2. 每次打开页面（刷新）之后，先判断是否存在之前的位置记录
      this.init();

      this.addEvent();
    }
    init(){
      // 读数据
      // let str = localStorage.getItem("pos") || ""
      // let str = sessionStorage.getItem("pos") || "";
      let str = cookie.get("pos") || "";

      // 根据存储的数据格式，解析字符串中有价值的信息
      // 如何解析取决于当初存的字符格式
      str = str.slice(1, -1);
      const obj = {};
      str.split(",").forEach(val=>{
        obj[val.split(":")[0]] = val.split(":")[1];
      })

      // 将解析之后的信息，应用
      this.ele.style.left = obj.x + "px";
      this.ele.style.top = obj.y + "px";
    }
    addEvent(){
      const that = this;
      this.ele.onmousedown = function(eve){
        that.downE = eve || window.event;
        document.onmousemove = function(eve){
          that.moveE = eve || window.event;
          that.move();
        }
        document.onmouseup = function(){
          that.up()
        }
      }
    }
    move(){
      this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
      this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
    }
    up(){
      document.onmousemove = null;
      document.onmouseup = null;
      // 1. 鼠标抬起时将当前元素的位置记录下来
      this.setPos();
    }
    setPos(){
      // 准备要存储的数据，注意将来的需要根据当前字符格式解析
      const json = `{x:${this.ele.offsetLeft},y:${this.ele.offsetTop}}`;

      // 存数据
      // localStorage.setItem("pos", json)
      // sessionStorage.setItem("pos", json)
      cookie.set("pos", json)
    }
  }

  new Drag;
  
</script>
</html>